﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using ServiceRss.Models;
using WebMatrix.WebData;
using System.Web.Security;
using ServiceRss.Filters;

using System.Xml;
using System.ServiceModel.Syndication;
using RssMVC4.Models;
using System.Xml.Schema;
using System.Net;

namespace ServiceRss
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ServiceRss" in code, svc and config file together.
   
    public class ServiceRss : IServiceRss
    {
        private LoginModel _loginModel;

        public System.Web.Security.MembershipCreateStatus LogOn(LoginModel model)
        {
            if (model == null || model.UserName == "" || model.Password == "")
                return MembershipCreateStatus.InvalidUserName;

            bool connected = Membership.ValidateUser(model.UserName, model.Password);

            if (connected == true)
            {
                _loginModel = model;
                return MembershipCreateStatus.Success;
            }
            return MembershipCreateStatus.InvalidUserName;
        }

        public System.Web.Security.MembershipCreateStatus CreatAccountAndConnect(Models.RegisterModel model)
        {
            try
            {
                if (model.UserName == "" || model.Password == "")
                    return MembershipCreateStatus.UserRejected;
                if (!model.Password.Equals(model.ConfirmPassword))
                    return MembershipCreateStatus.InvalidPassword;
                _loginModel = new LoginModel { UserName = model.UserName, Password = model.Password};
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

                using (RSSEntities _db = new RSSEntities())
                {
                    FeedManagers Manager = new FeedManagers()
                    {
                        UserName = model.UserName,
                    };
                    _db.FeedManagers.Add(Manager);
                    _db.SaveChanges();
                }
            }
            catch (MembershipCreateUserException e)
            {
                return MembershipCreateStatus.DuplicateUserName;
            }
            return MembershipCreateStatus.Success;
        }

        public bool IsValidUri(string uri)
        {
            UriKind uriKind = UriKind.Absolute;
     
            bool test = Uri.IsWellFormedUriString(uri, uriKind);
            return test;
        }

        public List<Flux> GetFlux(LoginModel model)
        {
           /* try
            {*/
                bool connected = Membership.ValidateUser(model.UserName, model.Password);
                if (connected == false)
                {
                    MembershipCreateUserException ex = new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName);
                    throw ex;
                }
                  List<Flux> listFlux = new List<Flux>();
                using (var _db = new RSSEntities())
                {
                    FeedManagers Manager = _db.FeedManagers.SingleOrDefault(U => U.UserName == model.UserName);

                  

                    foreach (var item in Manager.Feeds)
                    {
                        try
                        {

                            XmlReader reader = XmlReader.Create(item.Url);

                            SyndicationFeed rssData = SyndicationFeed.Load(reader);
                            DateTimeOffset date = rssData.Items.First().PublishDate;

                            int i = item.DateRead.CompareTo(date);
                            bool read = true;
                            if (i < 0)
                                read = false;

                            Flux flux = new Flux();
                            flux.ID = item.Id;
                            flux.Title = item.Title;
                            flux.Link = item.Url;
                            flux.isRead = read;
                            listFlux.Add(flux);
                        }
                        catch (NotSupportedException e)
                        {
                            Flux flux = new Flux();
                            flux.ID = item.Id;
                            flux.Title = item.Title;
                            flux.Link = item.Url;
                            flux.isRead = true;
                            listFlux.Add(flux);
                            continue;
                        }
                        catch (WebException ex)
                        {
                            Flux flux = new Flux();
                            flux.ID = item.Id;
                            flux.Title = item.Title;
                            flux.Link = item.Url;
                            flux.isRead = true;
                            listFlux.Add(flux);
                            continue;
                        }
                      
                    }
                    return listFlux;
                }
            //}
          
         /*   catch (InvalidOperationException e)
            {
                return listFlux;
            }*/
        }

        public List<Rss> GetRss(LoginModel model, Flux flux)
        {
            bool connected = Membership.ValidateUser(model.UserName, model.Password);
            if (connected == false)
            {
                MembershipCreateUserException ex = new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName);
                throw ex;
            }

            using (var _db = new RSSEntities())
            {
                Feeds feed = _db.Feeds.Find(flux.ID);

                feed.DateRead = DateTimeOffset.Now;
                feed.isRead = true;
                _db.SaveChanges();

                string f = feed.Url;

                try
                {
                    XmlReader reader = XmlReader.Create(f);

                    SyndicationFeed rssData = SyndicationFeed.Load(reader);

                    List<Rss> listRss = new List<Rss>();

                    foreach (var sItem in rssData.Items)
                    {
                        Rss rss = new Rss()
                        {
                            Title = sItem.Title.Text,
                            Link = sItem.Links.First().Uri.ToString(),
                            Description = sItem.Summary.Text
                        };
                        listRss.Add(rss);
                    }
                    return listRss;
                }
                catch (Exception ex)
                {
                    List<Rss> listRss = new List<Rss>();
                    Rss rss = new Rss { Title = "Error Rss Parse", Link = "", Description = "Exception: " + ex.Message };
                    listRss.Add(rss);
                    return listRss;
                }

            }
        }

        public FluxStatus AddRss(LoginModel model, RegisterRss newRss)
        {
            bool connected = Membership.ValidateUser(model.UserName, model.Password);
            if (connected == false)
            {
                return FluxStatus.CreatAnAccountBefore;
            }

            using (RSSEntities _db = new RSSEntities())
            {
                if (newRss.Title == null || !IsValidUri(newRss.Link))
                {
                    return FluxStatus.CreatAnAccountBefore;
                }

                FeedManagers Manager = _db.FeedManagers.FirstOrDefault(U => U.UserName == newRss.UserName);
                if (Manager != null)
                {
                    try
                    {
                        Feeds feed = new Feeds() { Title = newRss.Title, Url = newRss.Link, isRead = false, DateRead = DateTime.Now.AddYears(-1) };
                        Manager.Feeds.Add(feed);
                        _db.SaveChanges();
                        return FluxStatus.Success;
                    }
                    catch (InvalidOperationException ex)
                    {
                        return FluxStatus.InternalError;
                    }
                }
            }
            return FluxStatus.InternalError;
        }

        public FluxStatus RemoveRss(LoginModel model, DeleteRss deleteRss)
        {
            bool connected = Membership.ValidateUser(model.UserName, model.Password);
            if (connected == false)
            {
                return FluxStatus.CreatAnAccountBefore;
            }
            using (RSSEntities _db = new RSSEntities())
            {
                FeedManagers Manager = _db.FeedManagers.FirstOrDefault(U => U.UserName == deleteRss.UserName);

                Feeds FeedToRemove = Manager.Feeds.SingleOrDefault(F => F.Id == deleteRss.IdFlux);
                _db.Feeds.Remove(FeedToRemove);
                _db.SaveChanges();
                return   FluxStatus.Success;
            }
        }

        public FluxStatus EditRss(LoginModel model, EditFlux editRss)
        {
            bool connected = Membership.ValidateUser(model.UserName, model.Password);
            if (connected == false)
            {
                return FluxStatus.CreatAnAccountBefore;
            }
            if (editRss.Title == null || !IsValidUri(editRss.Link))
            {
                return FluxStatus.CreatAnAccountBefore;
            }
            using (RSSEntities _db = new RSSEntities())
            {
                if (editRss.ID > 0)
                {
                    Feeds flux = _db.Feeds.Find(editRss.ID);
                    flux.Title = editRss.Title;
                    flux.Url = editRss.Link;
                    _db.SaveChanges();
                    return FluxStatus.Success;
                }
                return FluxStatus.InternalError;
            }
        }
    }
}
